package com.example.chcrm.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.chcrm.entity.common.BasicDoc;
import com.example.chcrm.entity.common.OperateRecord;
import com.example.chcrm.entity.common.RandomHelper;
import com.example.chcrm.entity.common.ResponseMsg;
import com.example.chcrm.entity.employee.*;
import com.example.chcrm.mapper.*;
import com.example.chcrm.service.EssEmployeeService;
import org.apache.commons.lang3.StringUtils;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.servlet.ModelAndView;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @Author 邹
 * @Date 2025/3/4 10:15
 * @Version 1.0
 */
@Service
public class EssEmployeeServiceImpl<T> implements EssEmployeeService<T> {

    @Autowired
    private EssEmployeeMapper employeeMapper;
    @Autowired
    private DepartmentMapper departmentMapper;
    @Autowired
    private RoleModelsMapper roleModelsMapper;
    @Autowired
    private EssEmployeeDeptMapper employeeDeptMapper;   //用户部门中间表mapper
    @Autowired
    private EssEmployeeRoleMapper employeeRoleMapper;   //用户角色中间表mapper
    @Autowired
    private EssEmployeePortMapper employeePortMapper;   //用户角色中间表mapper
     @Autowired
    private OperateRecordMapper operateRecordMapper;   //用户角色中间表mapper
    @Autowired
    private SupplierPortMapper supplierPortMapper;   //用户角色中间表mapper


    @Override
    @Transactional
    public ResponseMsg<Object> login(EssEmployee request) {
        ResponseMsg<Object> response = new ResponseMsg<>();

        // 根据账号查询用户
        EssEmployee user = employeeMapper.selectOne(new QueryWrapper<EssEmployee>().eq("account", request.getAccount()));

        if (user == null) {
            response.fail("账号不存在！");
            return response;
        }

        // 校验密码（假设密码未加密，仅作示例）
        if (!user.getPassword().equals(request.getPassword())) {
            response.fail("密码错误！");
            return response;
        }

        // 检查用户状态
        if ("0".equals(user.getStatus()) || "2".equals(user.getStatus())) {
            response.fail("用户被禁用！");
            return response;
        }

        // 登录成功
        response.success("登录成功！");
        response.setData(user); // 可返回用户信息，前端根据需要决定是否使用
        return response;
    }

    @Override
    @Transactional
    public ResponseMsg<IPage<EssEmployee>> pageList(EssEmployee employee) {
        ResponseMsg<IPage<EssEmployee>> iPageResponseMsg = new ResponseMsg<>();
        List<EssEmployee> list = employeeMapper.pageList(employee);
        Page<EssEmployee> page = new Page<>();
        page.setRecords(list);
        page.setTotal(list.size());
        page.setSize(employee.getRows());
        page.setCurrent(employee.getPage());
        iPageResponseMsg.setData(page);
        iPageResponseMsg.success("查询成功");
        return iPageResponseMsg;
    }

    @Override
    @Transactional
    public ResponseMsg<Object> add(EssEmployee employee, EmployeeVo empVo) {
        ResponseMsg<Object> msg = new ResponseMsg<>();
        //验证账号是否重复
        int accountCount = (employeeMapper.selectCount(new QueryWrapper<EssEmployee>()
                .eq("account", employee.getAccount())
                .eq("is_deleted", 0))).intValue();
        if (accountCount > 0) {
            msg.fail("添加失败，登录账号已存在");
            return msg;
        }
        //验证部门是否存在
        Department department = departmentMapper.selectById(employee.getDepId());
        if (department == null || department.getIsDeleted() != 0) {
            msg.fail("添加失败，部门未存在");
            return msg;
        }
        //验证角色是否存在
        RoleModels role = roleModelsMapper.selectById(employee.getRoleId());
        if (role == null || role.getIsDeleted() != 0) {
            msg.fail("添加失败，角色未存在");
            return msg;
        }

        String empId = RandomHelper.uuid();
        employee.setId(empId);
        employee.setSource("0");
        employee.setUserName(employee.getEmpNm());
//        employee.setPassword(MD5.sign(employee.getPassword(), "utf-8"));
        employee.setPassword(employee.getPassword());
        employee.setStatus(1);
        employee.setIsDeleted("0");
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        employee.setCreateTime(sdf.format(new Date()));
        employeeMapper.insert(employee);
        //给用户添加部门
        EssEmployeeDept dept = new EssEmployeeDept();
        dept.setId(RandomHelper.uuid());
        dept.setDepId(department.getId());
        dept.setEmpId(empId);
        employeeDeptMapper.insert(dept);
        //给用户添加角色
        EssEmployeeRole employeeRole = new EssEmployeeRole();
        employeeRole.setId(RandomHelper.uuid());
        employeeRole.setRoleId(role.getId());
        employeeRole.setEmpId(empId);
        employeeRoleMapper.insert(employeeRole);

        //添加服务港口
        if (employee.getEmployeePorts() != null && employee.getEmployeePorts().size() > 0) {
            for (EssEmployeePort employeePort : employee.getEmployeePorts()) {
                if (!StringUtils.isNotBlank(employeePort.getPortId())) {
                    msg.fail("港口id不能为空");
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    return msg;
                }
                String  portName = (supplierPortMapper.selectById(employeePort.getPortId()).getPortName());
                employeePort.setPortName(portName);
                employeePort.setId(RandomHelper.uuid());
                employeePort.setEmpId(empId);
                employeePortMapper.insert(employeePort);
            }
        }
        //添加操作日志
        OperateRecord ope = new OperateRecord();
        ope.setId(RandomHelper.uuid());
        ope.setOperateType(OperateRecord.OPE_ADD);
        if (empVo != null) {
            ope.setOperationId(empVo.getId());
            ope.setOperationName(empVo.getEmpNm());
        }
        ope.setCreateTime(sdf.format(new Date()));
        ope.setSourceId(empId);
        operateRecordMapper.insert(ope);

        msg.success("添加成功");
        return msg;
    }

    @Override
    @Transactional
    public ResponseMsg<Object> disable(EssEmployee essEmployee, EmployeeVo empVo) {
        ResponseMsg<Object> msg = new ResponseMsg<>();
        if (StringUtils.isBlank(essEmployee.getId())){
            msg.fail("未找到选中用户");
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return msg;
        }
        UpdateWrapper updateWrapper=  new UpdateWrapper<EssEmployee>();

        if (essEmployee.getStatus()==1){
            updateWrapper.set("status",1);
            updateWrapper.eq("id",essEmployee.getId());
            employeeMapper.update(null,updateWrapper);
            msg.success("启动成功");
        }else if(essEmployee.getStatus()==0){
            updateWrapper.set("status",0);
            updateWrapper.eq("id",essEmployee.getId());
            employeeMapper.update(null,updateWrapper);
            msg.success("禁用成功");
        }else {
            msg.fail("本次操作失败");
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }
        //添加操作日志
        OperateRecord ope = new OperateRecord();
        ope.setId(RandomHelper.uuid());
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        ope.setCreateTime(sdf.format(new Date()));
        ope.setOperateType("修改状态");
        if (empVo != null) {
            ope.setOperationId(empVo.getId());
            ope.setOperationName(empVo.getEmpNm());
        }

        ope.setSourceId(essEmployee.getId());
        operateRecordMapper.insert(ope);
        return msg;
    }

    @Override
    @Transactional
    public ResponseMsg<Object> update(EssEmployee employee, EmployeeVo empVo) {
        ResponseMsg<Object> msg = new ResponseMsg<>();
        //查询用户是否存在
        EssEmployee oldEmployee = employeeMapper.selectById(employee.getId());
        if (oldEmployee == null || oldEmployee.getIsDeleted().equals(-1)) {
            msg.fail("修改失败，用户未找到");
            return msg;
        }
        //验证部门是否存在
        Department department = departmentMapper.selectById(employee.getDepId());
        if (department == null || department.getIsDeleted() != 0) {
            msg.fail("添加失败，部门已存在");
            return msg;
        }
        //验证角色是否存在
        RoleModels role = roleModelsMapper.selectById(employee.getRoleId());
        if (role == null || role.getIsDeleted() !=0) {
            msg.fail("添加失败，角色已存在");
            return msg;
        }
        oldEmployee.setEmpNm(employee.getEmpNm());
        oldEmployee.setEmpGender(employee.getEmpGender());
        oldEmployee.setAge(employee.getAge());
        oldEmployee.setEmail(employee.getEmail());
        employeeMapper.updateById(oldEmployee);
        //删除部门
        employeeDeptMapper.delete(new QueryWrapper<EssEmployeeDept>()
                .eq("emp_id", oldEmployee.getId()));
        //删除角色
        employeeRoleMapper.delete(new QueryWrapper<EssEmployeeRole>()
                .eq("emp_id", oldEmployee.getId()));
        //删除服务港口
        employeePortMapper.delete(new QueryWrapper<EssEmployeePort>()
                .eq("emp_id", oldEmployee.getId()));
        //给用户添加部门
        EssEmployeeDept dept = new EssEmployeeDept();
        dept.setId(RandomHelper.uuid());
        dept.setDepId(department.getId());
        dept.setEmpId(oldEmployee.getId());
        employeeDeptMapper.insert(dept);
        //给用户添加角色
        EssEmployeeRole employeeRole = new EssEmployeeRole();
        employeeRole.setId(RandomHelper.uuid());
        employeeRole.setRoleId(role.getId());
        employeeRole.setEmpId(oldEmployee.getId());
        employeeRoleMapper.insert(employeeRole);

        //添加服务港口
        if (employee.getEmployeePorts() != null && employee.getEmployeePorts().size() > 0) {
            for (EssEmployeePort employeePort : employee.getEmployeePorts()) {
                if (!StringUtils.isNotBlank(employeePort.getPortId())) {
                    msg.fail("港口id不能为空");
                    return msg;
                }
                String  portName = (supplierPortMapper.selectById(employeePort.getPortId()).getPortName());
                employeePort.setPortName(portName);
                employeePort.setId(RandomHelper.uuid());
                employeePort.setEmpId(oldEmployee.getId());
                employeePortMapper.insert(employeePort);
            }
        }
        //添加操作日志
        OperateRecord ope = new OperateRecord();
        ope.setId(RandomHelper.uuid());
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        ope.setCreateTime(sdf.format(new Date()));
        ope.setOperateType(OperateRecord.OPE_UPDATE);
        if (empVo != null) {
            ope.setOperationId(empVo.getId());
            ope.setOperationName(empVo.getEmpNm());
        }

        ope.setSourceId(oldEmployee.getId());
        operateRecordMapper.insert(ope);
        msg.success("修改成功");
        return msg;
    }

    @Override
    @Transactional
    public ResponseMsg<Object> reset(EssEmployee essEmployee, EmployeeVo empVo) {
        UpdateWrapper<EssEmployee> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("id",essEmployee.getId()).set("password",666666);
        employeeMapper.update(null,updateWrapper);
        //添加操作日志
        OperateRecord ope = new OperateRecord();
        ope.setId(RandomHelper.uuid());
        ope.setOperateType("重置密码");
        if (empVo != null) {
            ope.setOperationId(empVo.getId());
            ope.setOperationName(empVo.getEmpNm());
        }
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        ope.setCreateTime(sdf.format(new Date()));
        ope.setSourceId(essEmployee.getId());
        operateRecordMapper.insert(ope);
        ResponseMsg<Object> msg = new ResponseMsg<>();
        msg.success("重置成功");
        return msg;
    }

    @Override
    public ResponseMsg<Object> userInfo(EmployeeVo empVo) {
        ResponseMsg<Object> msg = new ResponseMsg<>();
        EssEmployee essEmployee2 = employeeMapper.selectOne(new QueryWrapper<EssEmployee>()
                .eq("emp_name",empVo.getEmpNm()));
        String id = essEmployee2.getId();
        EssEmployee essEmployee = employeeMapper.getUserById(id);
        if (essEmployee != null) {
            //服务港口查询
            List<EssEmployeePort> employeePortList = employeePortMapper.selectList(new QueryWrapper<EssEmployeePort>()
                    .eq("emp_id", id));
            essEmployee.setEmployeePorts(employeePortList);
            //查询操作记录
            List<OperateRecord> operateRecords = operateRecordMapper.selectList(new QueryWrapper<OperateRecord>()
                    .eq("sourceId", essEmployee.getId())
                    .orderByDesc("create_time"));
            essEmployee.setOperateRecordList(operateRecords);
        }
        msg.setData(essEmployee);
        msg.success("查询成功");
        return msg;
    }

    @Override
    public ResponseMsg<Object> detail(String id) {
        ResponseMsg<Object> msg = new ResponseMsg<>();
        EssEmployee essEmployee = employeeMapper.getUserById(id);
        if (essEmployee != null) {
            //服务港口查询
            List<EssEmployeePort> employeePortList = employeePortMapper.selectList(new QueryWrapper<EssEmployeePort>()
                    .eq("emp_id", id));
            essEmployee.setEmployeePorts(employeePortList);
            //查询操作记录
            List<OperateRecord> operateRecords = operateRecordMapper.selectList(new QueryWrapper<OperateRecord>()
                    .eq("sourceId", essEmployee.getId())
                    .orderByDesc("create_time"));
            essEmployee.setOperateRecordList(operateRecords);
        }
        msg.setData(essEmployee);
        msg.success("查询成功");
        return msg;
    }

    @Override
    public ModelAndView userExport(EssEmployee employeeVo, EmployeeVo empVo) {
        List<Map<String, Object>> essList = employeeMapper.userist(employeeVo);
        System.out.println(essList);
        //循环区分用户类型
        for (int i = 0, lenght = essList.size(); i < lenght; i++) {
            switch (essList.get(i).get("source").toString()) {
                case "0":
                    essList.get(i).put("source", "平台");
                    break;
                case "1":
                    essList.get(i).put("source", "公路供应商");
                    break;
                case "2":
                    essList.get(i).put("source", "水路供应商");
                    break;
                case "3":
                    essList.get(i).put("source", "司机");
                    break;
                case "4":
                    essList.get(i).put("source", "船舶");
                    break;
            }
            essList.get(i).put("status", this.verifyStatus(essList.get(i).get("status").toString()));
        }
        //导出
        ModelAndView modelAndView = new ModelAndView(new JeecgEntityExcelView());
        modelAndView.addObject(NormalExcelConstants.FILE_NAME, "用户表");
        modelAndView.addObject(NormalExcelConstants.CLASS, EssEmployee.class);
        if ( empVo !=null && empVo.getEmpNm() != null ) {
            modelAndView.addObject(NormalExcelConstants.PARAMS, new ExportParams("用户表", "导出人:" + empVo.getEmpNm(), "导出信息"));
        } else {
            modelAndView.addObject(NormalExcelConstants.PARAMS, new ExportParams("用户表", "导出人:" + "无登录导出", "导出信息"));
        }
        modelAndView.addObject(NormalExcelConstants.DATA_LIST, essList);
        return modelAndView;
    }

    /**
     * 导出校验审核状态
     **/
    public String verifyStatus(String isEnable) {
        String state = "";
        switch (isEnable) {
            case "0":
                state = "禁用";
                break;
            case "1":
                state = "启用";
                break;
            case "2":
                state = "待审核";
                break;
        }
        return state;
    }

    /**
     * 修改登录用户密码
     *
     * @param oldPwd
     * @param newPwd
     * @param empVo
     * @return
     */
    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public ResponseMsg<Object> updatePassword(String oldPwd, String newPwd, EmployeeVo empVo) {
        ResponseMsg<Object> msg = new ResponseMsg<>();
        EssEmployee essEmployee2 = employeeMapper.selectOne(new QueryWrapper<EssEmployee>()
                .eq("emp_name",empVo.getEmpNm()));
        String id = essEmployee2.getId();
        //查询用户是否存在
        EssEmployee oldEmployee = employeeMapper.selectById(id);
        if (oldEmployee == null || !oldEmployee.getIsDeleted().equals(BasicDoc.NOT_DELETE + "")) {
            msg.fail("操作失败，登录失效");
            return msg;
        }
        //验证原始密码是否正确
        int num = employeeMapper.selectCount(new QueryWrapper<EssEmployee>()
                .eq("id", oldEmployee.getId())
                .eq("password", oldPwd)
                .eq("is_deleted", BasicDoc.NOT_DELETE + "")).intValue();
        if (num != 1) {
            msg.fail("操作失败，原始密码不正确");
            return msg;
        }
        oldEmployee.setPassword(newPwd);
        employeeMapper.updateById(oldEmployee);
        String key = empVo.getAccount() + "," + empVo.getSource() + ",1";
        //操作日志
        OperateRecord ope = new OperateRecord();
        ope.setId(RandomHelper.uuid());
        ope.setOperateType("修改密码");
        ope.setSourceId(oldEmployee.getId());
        if (empVo !=null){
            ope.setOperationName(empVo.getEmpNm());
            ope.setOperationId(empVo.getId());
        }
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        ope.setCreateTime(sdf.format(new Date()));
        operateRecordMapper.insert(ope);
        msg.success("修改成功");
        return msg;
    }
}

